import os
import sys
import re
import shutil

def getfilelist(filepath, tabnum=1):  
    simplepath = os.path.split(filepath)[1]  
    returnstr = simplepath+"<>"+"\n"  
    returndirstr = ""  
    returnfilestr = ""  
    filelist = os.listdir(filepath)  
    for num in range(len(filelist)):  
        filename=filelist[num]    
        if os.path.isdir(filepath+"/"+filename):  
            returndirstr += "\t"*tabnum+getfilelist(filepath+"/"+filename, tabnum+1)  
        else:
            if filename.find('.csd') >= 0:
                returnfilestr += "\t"*tabnum+filepath+"/"+filename+"\n"
            elif filename.find('.png') >= 0:
                returnfilestr += "\t"*tabnum+simplepath+"/"+filename+"\n"
            else: 
                returnfilestr += "\t"*tabnum+filename+"\n"
    
    returnstr += returnfilestr+returndirstr
    
    return returnstr+"\t"*tabnum+"</>\n"

def getDir():
    '''
    path = raw_input("please set the path of output file:")  
    usefulpath = path.replace('\\', '/')  
    if usefulpath.endswith("/"):  
        usefulpath = usefulpath[:-1]
    '''
    usefulpath = sys.path[0]
    if not os.path.exists(usefulpath):  
        print "path error!";
    elif not os.path.isdir(usefulpath):  
        print "it is not a folder!";
    else:  
        filelist = os.listdir(usefulpath)  
        o=open("dir.xml","w+")  
        o.writelines(getfilelist(usefulpath))  
        o.close()  
        print "Dir has export! please see dir.xml"

def countPic():
    fullpath = sys.path[0]
    listfile = os.listdir(fullpath)
	
    #sava data
    dict = {}
    csdDict = {}
    
    plistFile = open(fullpath + "/dir.xml", 'r')
    
    for line in plistFile:
        picName = "/" + getPicName(line).strip()
        if picName != '' :
            dict[picName] = 0

        csdName = getCsdName(line).strip()
        if csdName != "":
            csdDict[csdName] = 0
            

    #print dict.items();
    #print csdDict.items();
    
    plistFile.close()
	
    calcPicCount(csdDict, dict)
            
    output = open(fullpath + "/output.txt", 'w')

    listDict = sorted(dict.items(),key=lambda e:e[1],reverse = False)
    
    for item in listDict:
        output.write(str(item) + '\n')
        #output.write(name + '\t\t\t\t\t' + str(id) + '\n')
        
    output.close()
    
def getPicName(line):
    findFile = line.find('.png')
    if findFile >= 0 :
        return line
    
    return ''

def getCsdName(line):
    findFile = line.find('.csd')
    if findFile >= 0 :
        return line
    
    return ''


def calcPicCount(csdDict, dict):    
    for csdName in csdDict.keys():
        print csdName;
        for picName in dict.keys():
            if isUsedInFile(csdName, picName):
                dict[picName] = dict[picName] + 1
                
    print "sources search finish! please see output.txt" 
    
def isUsedInFile(file, picName):
    input = open(file, 'r')
    inputAll = input.read()
    findRes = inputAll.find(picName)
    input.close()
    return findRes >= 0
    
    
# -------------- main --------------
getDir()
countPic()
